<template>
  <!-- 设置 -->
  <div class="chatSet">
    <!-- 群名称 -->
    <div class="Group-name">
      <p>{{ currentChat.name }}</p>
      <div class="edit" v-if="currentChat.type == 0" @click="dialogFormVisible = true">修改</div>
    </div>
    <p class="member" v-if="currentChat.type == 0">
      <span>群成员</span>
      <span>{{ groupMeber.length }} 人</span>
    </p>
    <!-- 搜索 -->
    <el-input
      v-model="name"
      placeholder="搜索"
      prefix-icon="el-icon-search"
    ></el-input>
    <div v-if="showBtnAddBread">
      <!-- 添加删除按钮 -->
      <div class="add-del" v-if="showAddDel" ref="AddDelBtn">
        <!-- 添加成员 -->
        <p class="add-Concat">
          <!-- <i class="el-icon-circle-plus-outline"></i> -->
          <img src="@/assets/images/tj_icon.png" alt="" @click="addConcat" />
          <span>添加群成员</span>
        </p>
        <!-- 删除成员 -->
        <p class="del-Concat">
          <!-- <i class="el-icon-remove-outline"></i> -->
          <img src="@/assets/images/sc_icon.png" alt="" @click="delConcat" />
          <span>删除群成员</span>
        </p>
      </div>
      <!-- 面包屑 -->
      <p v-if="addBread" class="el-breadcrumb">
        <span @click="addMB">群成员</span> > <span>添加群成员</span>
      </p>
      <p v-if="delBread" class="el-breadcrumb">
        <span @click="delMB">群成员</span> > <span>删除群成员</span>
      </p>
    </div>
    <!-- 群成员列表 -->
    <div class="group-list">
      <!-- 删除的 -->
      <ul v-if="delBread">
        <template v-for="(groupItem, groupIndex) in groupListArr">
          <li :key="groupIndex" v-if="groupItem.status != -1">
            <!-- 盒子 -->
            <el-checkbox
              label=""
              id="checkbox"
              v-model="groupItem.istrue"
            >
              <!-- 头像 -->
              <el-avatar
                class="avatar"
                :src="groupItem.avatar == '' ? DeAvatar : groupItem.avatar"
                :size="32"
              ></el-avatar>
              <p>
                <!-- 名字 -->
                <span>{{ groupItem.nickName }}</span>
                <!-- 职务 -->
                <!-- <span>{{ getUsrType(groupItem.usertype) }}</span> -->
              </p>
            </el-checkbox>
          </li>
        </template>
      </ul>
      <!-- 添加时 -->
      <ul v-else-if="addCheck">
        <li
          v-for="(canGroupItem, canGroupIndex) in getCanMember || []"
          :key="canGroupIndex"
        >
          <!-- 盒子 -->
          <!-- 盒子 -->
          <el-checkbox label="" v-model="canGroupItem.istrue">
            <!-- 头像 -->
            <el-avatar
              class="avatar"
              :src="canGroupItem.avatar == '' ? DeAvatar : canGroupItem.avatar"
              :size="32"
            ></el-avatar>
            <p>
              <!-- 名字 -->
              <span>{{ canGroupItem.nickName }}</span>
              <!-- 职务 -->
              <!-- <span>{{ getUseTypeS(canGroupItem.userType) }}</span> -->
            </p>
          </el-checkbox>
        </li>
      </ul>
      <!-- 默认的 -->
      <ul v-else>
        <template v-for="(groupItem, groupIndex) in groupListArr">
          <li :key="groupIndex" v-if="groupItem.status != -1">
            <!-- 盒子 -->
            <!-- 头像 -->
            <el-avatar
              class="avatar"
              :src="groupItem.avatar == '' ? DeAvatar : groupItem.avatar"
              :size="32"
            ></el-avatar>
            <p>
              <!-- 名字 -->
              <span>{{ groupItem.nickName }}</span>
              <!-- 职务 -->
              <!-- <span>{{ getUsrType(groupItem.usertype) }}</span> -->
            </p>
          </li>
        </template>
      </ul>
    </div>
    <button
      class="add-btn"
      v-if="showAddConcat"
      @click="addBtn(currentChat.orderNo)"
    >
      添加
    </button>
    <button
      class="del-btn"
      v-if="showDelConcat"
      @click="delBtn(currentChat.orderNo)"
    >
      删除
    </button>

    <!-- 修改群名 -->
    <el-dialog title="修改群名" width="30%" :visible.sync="dialogFormVisible">
      <el-form>
      <el-input v-model="editNameInput" autocomplete="off" placeholder="请输入群名"></el-input>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button class="editBut" type="warning" @click="editName()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getList,
  getMembers,
  AddDelMembers,
  getName,
  updateImSessionApi,
} from "@/BMViews/api/upload/index.js";
import { mapGetters } from "vuex";
export default {


  data() {
    return {
      // 默认头像src\assets\images\defaultAvatar.jpg
      DeAvatar: require("@/assets/images/defaultAvatar.jpg"),
      arr: [], //所选中的复选框
      // 群成员列表搜索
      name: "",
      // 判断邀请的是用户还是商务
      isUserBus: "",
      // 群成员列表
      groupList: [],
      filerList: [],
      friend: [],
      groupMeber: [],
      groupListArr: [],
      type: {},
      // 可添加的人员
      getCanMember: [],
      // 当前聊天的群
      // currentChat: { title: "", id: "", color: "", orderNo: "" },
      // 控制两个按钮
      showAddDel: true,
      // 是否显示可以添加删除成员按钮
      showBtnAddBread: false,
      addCheck: false,
      // 删除成员
      delBread: false,
      // 添加成员面包屑
      addBread: false,
      // 添加成员
      showAddConcat: false,
      // 删除成员
      showDelConcat: false,
      dialogFormVisible:false,
      editNameInput:'',
    };
  },
  props:{
    //当前聊天室信息
    currentChat:{
      type: Object,
      default: ()=>{ return },
    },
  },
  watch: {

    //监听聊天室信息变化
    currentChat:{
      deep: !0,
      immediate: true,
      handler: function (newValue, oldValue) {
        console.log('1111111111111',newValue)
        //获取聊天记录
        if(!newValue) return false;
        this.showAddDel= true
        // 是否显示可以添加删除成员按钮
        this.showBtnAddBread= false
        this.addCheck= false
        // 删除成员
        this.delBread= false
        // 添加成员面包
        this.addBread= false
        // 添加成员
        this.showAddConcat= false
        // 删除成员
        this.showDelConcat= false
        this.getFriend();
      }
    }
  },
  created() {

  },

  mounted() {},
  computed: {
    ...mapGetters(["userType", "cmId", "circleId", "userId"]),
    getUsrType() {
      // 10自己注册 00系统注册 40跟单 50专家 60商务 65渠道 69商务和渠道 80实体 90专家助理
      return (type) => {
        if (type == "0") {
          return "用户";
        } else if (type == "1") {
          return "专家";
        } else if (type == "2") {
          return "商务专员";
        } else if (type == "3") {
          return "商务总监";
        } else if (type == "4") {
          return "商务经理";
        } else if (type == "5") {
          return "渠道专员";
        } else if (type == "6") {
          return "渠道总监";
        } else if (type == "7") {
          return "渠道经理";
        } else if (type == "8") {
          return "跟单";
        } else if (type == "9") {
          return "专家助理";
        } else if (type == "10") {
          return "圈子成员";
        } else {
          return "商务";
        }
      };
    },
  },
  methods: {
    //获取list里面的成员（members:{userid:;usertype:; original: ;}）
    async getFriend() {
      // const { code, data } = await getList({ id: this.currentChat.orderNo });
      this.friend = this.currentChat.members;
      let nameArr = [];
      console.log(this.friend, "9999999999999999999999");
      this.friend.forEach((item) => {
        nameArr.push(item.userid);
      });
      this.groupMeber = this.friend.filter((item) => {
        return item.status != -1;
      });
      // 传给聊天组件
      let aaa = await this.getMember(nameArr);
      // 找到id与自己相同的

      console.log(this.groupListArr,'2222222222222222222222');
      let type = this.groupListArr.find((item, index) => {
        return item.userid == this.userId;
      });
      console.log(type,'3333333333333333333');
      // 先隐藏
      this.showBtnAddBread = false;
      // 判断有没有权限删除添加成员;
      if (type.type == "0" && this.currentChat.type == 0) {
        this.showBtnAddBread = true;
      }
    },

    // //获取成员
    async getMember(name) {
      const { data } = await getName({ userIds: name?.join(",") });
      this.groupList = data;

      // 把usertype和是否是本群成员添加进去
      this.groupListArr = this.groupList.map((itemA, index) => {
        return { ...itemA, ...this.friend[index] };
      });
      this.filerList = this.groupListArr;
      return data;
      // console.log(this.groupListArr, "成员成员成员成员成员成员成员");
    },
    // 对象合并到数组里
    mergeObj(arr, obj) {
      return arr.map((item) => {
        return { ...item, ...obj };
      });
    },
    // 添加成员
    addConcat() {
      // 显示添加成员按钮（大小）
      this.showAddConcat = true;
      this.addBread = true;
      this.addCheck = true;
      this.showAddDel = false;
      this.delBread = false;
      this.getCanMembers();
    },
    // 删除成员
    delConcat() {
      this.showDelConcat = true;
      this.showAddDel = false;
      this.addBread = false;
      this.delBread = true;
    },

    //修改群名
    async editName(){
      if(!this.editNameInput) return;
      let ress = await updateImSessionApi({
        id: this.currentChat.id,
        name: this.editNameInput,
      });
      if(ress.code == 200){
        this.dialogFormVisible = false;
        // this.groupListArr.push(addMember);
        this.$message.success("修改成功！");
        // 添加成功之后重新调用接口
        this.$bus.$emit('updataImList', this.currentChat)
        // this.getFriend();
      }
    },

    // 添加完成后
    async addBtn(id) {

      // 点击添加判断是否选中

      if (this.getCanMember.length <= 0) {
        // console.log("000000000");
        await this.$confirm("无可邀请成员");
      }


      // 1.去循环判断是否选中 2.如果选中拿到它的id 3.把它push到数组
      try {
        if (this.getCanMember.length) {
          //当前已存在成员
          console.log(this.currentChat.members);
           let addList = this.getCanMember.filter((item) => item.istrue);
           console.log(addList,'444444444444444444');
          if (addList.length > 0) {
            // console.log(addList, "------------------------");
            let addMember = JSON.parse(JSON.stringify(this.currentChat.members))
            // let addMember = [];
            // console.log(this.isUserBus);
            addList.forEach((item) => {
              addMember.push({
                type: 1,
                usertype: item.userType,
                userid: item.userId,
                status: 0,
                nickName: item.nickName,
                joinTime: this.format(new Date()),
              });
            });
            this.$confirm("确定要邀请该成员吗？").then(async (res) => {
              console.log(res,'tanchuang');
              let ress = await updateImSessionApi({
                id: this.currentChat.id,
                members: addMember,
              });
              if(ress.code == 200){
                this.showAddConcat = false;
                this.showAddDel = true;
                this.delBread = false;
                this.addBread = false;
                this.addCheck = false;
                // this.groupListArr.push(addMember);
                this.$message.success("添加成功！");
                // 添加成功之后重新调用接口
                this.$bus.$emit('updataImList', this.currentChat)
                // this.getFriend();
              }
            }).catch(_ => {});

          }
        }
      } catch (err) {
        console.log(err);
      }
    },
    format(date,fmt = "yyyy-MM-dd hh:mm:ss") {
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    },
    // 删除完成后
    async delBtn(id) {

      // console.log(id);

      // 去循环拿到选中的成员id
      let deleteList = this.groupListArr
        .filter((item) => !item.istrue);
      let deleteLists = [];
      console.log(deleteList);
      deleteList.forEach((item) => {
        deleteLists.push({
          type: item.type,
          usertype: item.usertype,
          userid: item.userId,
          status: item.status,
          nickName: item.nickName,
          joinTime: item.joinTime,
        });
      });

      this.$confirm("确定要删除该成员吗？").then(async (res) => {
        let ress = await updateImSessionApi({
          id: this.currentChat.id,
          members: deleteLists,
        });
        if(ress.code == 200){
          this.showAddConcat = false;
          this.showAddDel = true;
          this.delBread = false;
          this.addBread = false;
          this.addCheck = false;
          // this.groupListArr.push(addMember);
          this.$message.success("添加成功！");
          // 添加成功之后重新调用接口
          this.$bus.$emit('updataImList', this.currentChat)
          this.getFriend();
        }
      }).catch(_ => {});
    },
    //获取第一二个汉字
    getHanzi(name) {
      if (name) {
        let arr = name.split("");
        let reg =
          /^(\d+$|[a-z]+$|[A-Z]+$|[` ~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$|((?=[!-~])[^\da-zA-Z])+$)/;
        let str = "";
        for (let i = 0; i < arr.length; i++) {
          if (!reg.test(arr[i])) {
            return arr[i] + arr[i + 1];
          }
        }
      }
    },

    // 获取可以添加的成员列表
    async getCanMembers() {

      //type 0用户 1商务
      let type = this.groupListArr.find((item, index) => {
        return item.userid == this.userId;
      });
      console.log('获取用户信息',type);
      // 先过滤掉已删除的人员（status=-1）（删除之后应该还可以添加）
      let delFriend = this.friend.filter((item) => {
        return item.status != -1;
      });
      // 添加完之后不能再在添加人员里面
      let filterArr = [];
      delFriend.forEach((item) => {
        filterArr.push(item.userid);
      });
      // 用户
      // console.log(this.circleId);
      const { data } = await getMembers({
        id: this.currentChat.circleId,
        type: 0,
      });
      this.getCanMember = data.filter((item) => {
        return filterArr.indexOf(item.userId) == -1;
      });

      // if (type.usertype == "0") {


      //   this.isUserBus = "10";
      //   // console.log(data, "8888888888888888888");
      //   // 商务
      // } else if (type.usertype == "2") {
      //   const { data } = await getMembers({
      //     id: this.currentChat.circleId,
      //     type: 1,
      //   });
      //   this.getCanMember = data.filter((item) => {
      //     return filterArr.indexOf(item.userId) == -1;
      //   });
      //   this.isUserBus = "11";
      //   // console.log(data);
      // } else {
      //   this.addBread = false;
      // }
    },
    // 面包屑返回
    addMB() {
      this.showAddDel = true;
      this.addBread = false;
      this.delBread = false;
      this.addCheck = false;
      this.delBread = false;
      this.showAddConcat = false;
      this.showDelConcat = false;
    },
    delMB() {
      this.showAddDel = true;
      this.addBread = false;
      this.delBread = false;
      this.addCheck = false;
      this.delBread = false;
      this.showAddConcat = false;
      this.showDelConcat = false;
    },
  },
  filters: {
    // 超出20字显示省略号
    ellipsis(value) {
      if (!value?.title) return "";
      if (value?.title.length > 20) {
        return value.title.slice(0, 20) + "...";
      }
      return value;
    },
  },
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}

ul li {
  list-style: none;
}
.chatSet {
  margin: 0 16px;
}
/* 群成员 */
.member {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  margin-bottom: 15px;
}
.member span:nth-child(1) {
  color: #516179;
  font-size: 14px;
}
.member span:nth-child(2) {
  color: #9c9c9c;
  font-size: 12px;
}
.Group-name {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  padding-top: 10px;
  border-bottom: 2px solid #efefef;
}
.Group-name .edit{
  font-size:12px;
  color:#f87a23;
  white-space:nowrap;
}
.Group-name .avatar {
  font-size: 12px;
  margin-right: 10px;
  border-radius: 8px;
}
.Group-name p {
  display: inline-block;
  font-size: 14px;
  font-weight: 700;
}
/* 添加删除人员 */
.add-del {
  margin-top: 15px;
}
.add-del p {
  margin-bottom: 10px;
}
.add-del p img {
  width: 32px;
  height: 32px;
  vertical-align: middle;
}
.add-del p span {
  display: inline-block;
  font-size: 14px;
  font-weight: 600;
  color: #232323;
  margin-left: 15px;
}
/* 群成员列表 */
.group-list {
  height: calc(100% - 226px);
  margin-top: 10px;
}
.group-list ul {
  height: 100%;
  overflow-y: auto;
}
.group-list ul li {
  display: flex;
  padding: 3px 0;
  margin-top: 4px;
}
::v-deep .el-checkbox__input {
  line-height: 32px;
}
.group-list ul li p {
  padding: 2px;
}
.group-list ul li p span {
  font-size: 14px;
  /* font-weight: 700; */
  margin-left: 10px;
}
.group-list ul li p span:nth-child(2) {
  /* font-weight: 400; */
  font-size: 12px;
  color: #878787;
  padding: 4px 6px;
  background: #efefef;
  border-radius: 2px;
}
.group-list ul:nth-child(2) p {
  padding: 0;
}
.group-list ul li .avatar {
  vertical-align: middle;
  /* margin-left: 16px; */
}
.group-list ul li .el-checkbox {
  display: flex;
  border-color: #f87a23;
  margin-right: 16px;
}
.editBut{
  background: #f87a23;
}
::v-deep .group-list ul li .el-checkbox .el-checkbox__label {
  display: flex;
}
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #f87a23;
  border-color: #f87a23;
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #f87a23;
}
/* 设置 */
::v-deep .el-breadcrumb {
  margin-top: 18px;
}
::v-deep .el-breadcrumb span:nth-child(1):hover {
  cursor: pointer;
  color: #f87a23;
}
.add-btn,
.del-btn {
  background-color: #f87a23;
  border-radius: 22px;
  width: 88%;
  height: 44px;
  box-sizing: border-box;
  border-color: #f87a23;
  border: none;
  color: #fff;
  font-size: 14px;
  position: absolute;
  bottom: 22px;
  left: 30px;
  z-index: 999;
}
.group-list {
  height: 92%;
  overflow-y: auto;
}

/* 滚动条 */
::-webkit-scrollbar {
  width: 0px; /*高宽分别对应横竖滚动条的尺寸*/
}

.el-button--medium {
    padding: 10px 20px !important;
}
</style>
